import { useState, useEffect } from 'react';
import { App, Table, Button, Space, Modal, Form, Input, message, Cascader } from 'antd';
import { MainLayout } from '~/layouts/MainLayout';
import { knowledgeApi, categoryApi } from '~/services/api';

export default function Knowledge() {
  const { message, modal } = App.useApp();
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [categories, setCategories] = useState<any[]>([]);
  const [editingRecord, setEditingRecord] = useState<any>(null);

  // 添加分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 修改 fetchData 方法
  const fetchData = async (page = 1, size = 10) => {
    setLoading(true);
    try {
      const res: any = await knowledgeApi.list({
        page,
        size
      });
      setData(res.data.items || []);
      setPagination({
        current: page,
        pageSize: size,
        total: res.data.total || 0
      });
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchCategories = async () => {
    try {
      const res = await categoryApi.list({});
      const formatCategories = (items: any[]) => {
        return items.map(item => ({
          label: item.name,
          value: item.id,
          isLeaf: false,
          level: item.level
        }));
      };
      setCategories(formatCategories(res.data?.items || []));
    } catch (error) {
      message.error('获取分类失败');
    }
  };

  const loadCategoryData = async (selectedOptions: any[]) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    try {
      const res = await categoryApi.list({
        parentId: targetOption.value,
        parentLevel: targetOption.level
      });
      const children = res.data?.items || [];
      targetOption.children = children.map((item: any) => ({
        label: item.name,
        value: item.id,
        isLeaf: children.length === 0 || item.level >= 6,
        level: item.level
      }));
    } catch (error) {
      message.error('加载子分类失败');
    }
    targetOption.loading = false;
    setCategories([...categories]);
  };

  const handleAdd = async ({ categoryIds = [], ...values }: any) => {
    try {
      const processedValues = { ...values };
      categoryIds.forEach((id: string, index: number) => {
        processedValues[`level${index + 1}Id`] = String(id);
      });
      await knowledgeApi.create(processedValues);
      message.success('创建成功');
      setVisible(false);
      form.resetFields();
      fetchData();
    } catch (error) {
      message.error('创建失败');
    }
  };

  const handleEdit = async ({ categoryIds = [], ...values }: any) => {
    try {
      const processedValues = { ...values };

      categoryIds.forEach((id: string, index: number) => {
        processedValues[`level${index + 1}Id`] = String(id);
      });

      // 确保 ID 是数字类型
      const id = parseInt(editingRecord.id);
      await knowledgeApi.update(id, processedValues);
      message.success('更新成功');
      setVisible(false);
      form.resetFields();
      setEditingRecord(null);
      fetchData();
    } catch (error) {
      console.error('Update error:', error);  // 添加错误日志
      message.error('更新失败');
    }
  };

  const handleDelete = async (id: number) => {
    modal.confirm({
      title: '确认删除',
      content: '确定要删除这条知识点吗？',
      onOk: async () => {
        try {
          await knowledgeApi.delete(id);
          message.success('删除成功');
          fetchData();
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  const loadEditCategories = async (record: any) => {
    const categoryIds = [];
    const loadedCategories = [...categories];

    for (let i = 1; i <= 6; i++) {
      const levelId = record[`level${i}Id`];
      if (levelId) {
        categoryIds.push(levelId.toString());
        if (i > 1) {
          // 加载上一级的子分类
          const parentId = record[`level${i - 1}Id`];
          const parentLevel = String(i - 1);
          const res = await categoryApi.list({
            parentId,
            parentLevel
          });
          const parentOption = findOptionById(loadedCategories, parentId);
          if (parentOption) {
            parentOption.children = (res.data?.items || []).map((item: any) => ({
              label: item.name,
              value: item.id,
              isLeaf: false,
              level: item.level
            }));
          }
        }
      }
    }

    setCategories(loadedCategories);
    return categoryIds;
  };

  const findOptionById = (options: any[], id: string): any => {
    for (const option of options) {
      if (option.value.toString() === id) {
        return option;
      }
      if (option.children) {
        const found = findOptionById(option.children, id);
        if (found) return found;
      }
    }
    return null;
  };


  useEffect(() => {
    fetchData();
    fetchCategories();
  }, []);

  const columns = [
    {
      title: '知识点ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '知识点Code',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '知识点名称',
      dataIndex: 'example',
      key: 'example',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      // 在 columns 定义中修改编辑按钮的 onClick 处理
      render: (_: any, record: any) => (
        <Space>
          <Button
            type="link"
            onClick={async () => {
              setEditingRecord(record);
              // 构建分类 ID 数组
              const categoryIds = await loadEditCategories(record);
              form.setFieldsValue({
                categoryIds, // 设置级联选择器的值
                knowledge_point_code: record.code,
                example: record.example,
                knowledge_point_desc: record.description,
              });
              setVisible(true);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <MainLayout>
      <div className="bg-white p-6 rounded-lg">
        <div className="flex justify-between mb-4">
          <h1 className="text-2xl">知识点管理</h1>
          <Button
            type="primary"
            onClick={() => {
              setEditingRecord(null);
              form.resetFields();
              setVisible(true);
            }}
          >
            新增知识点
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          rowKey={(record) => record.id?.toString()}
          loading={loading}
          pagination={{
            ...pagination,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              fetchData(page, pageSize);
            }
          }}
        />

        <Modal
          title={editingRecord ? '编辑知识点' : '新增知识点'}
          open={visible}
          onCancel={() => {
            setVisible(false);
            form.resetFields();
            setEditingRecord(null);
          }}
          footer={null}
          width={600}
        >
          <Form
            form={form}
            onFinish={editingRecord ? handleEdit : handleAdd}
            layout="vertical"
          >
            <Form.Item name="categoryIds" label="所属分类" rules={[{ required: true, message: '请选择分类' }]}>
              <Cascader
                options={categories}
                loadData={loadCategoryData}
                changeOnSelect
                placeholder="请选择分类"
              />
            </Form.Item>
            <Form.Item name="knowledge_point_code" label="代码（请保证唯一性）" rules={[{ required: true, message: '请输入知识点代码' }]}>
              <Input placeholder="请输入代码" />
            </Form.Item>
            <Form.Item name="example" label="知识点名称" rules={[{ required: true, message: '请输入知识点名称' }]}>
              <Input placeholder="请输入知识点名称" />
            </Form.Item>
            <Form.Item name="knowledge_point_desc" label="描述" rules={[{ required: true, message: '请输入知识点描述' }]}>
              <Input.TextArea rows={4} placeholder="请输入知识点描述" />
            </Form.Item>
            <Form.Item className="text-right mb-0">
              <Space>
                <Button onClick={() => {
                  setVisible(false);
                  form.resetFields();
                  setEditingRecord(null);
                }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit" loading={loading}>
                  确定
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </MainLayout>
  );
}